<?php
	/**
	* Shopping Cart Update: update product quantity in shopping cart
	* 
	* @author trungdt
	* @since Oct 19, 2011
	* 
	* Change logs
	* 
	*/

	if (!defined('EXPONENT')) exit('');

	$template=new template("productsmodule","_cart_view");
	if (!defined("ABProductsModule_Carts"))
		define("ABProductsModule_Carts","ABShopCart_SessionKey");

	$carts=exponent_sessions_get(ABProductsModule_Carts);
	if ($carts == null)
		$carts = array();

	$pid=0;
	$new_quantity=0;
	$myaction="";
	if (isset($_POST['pid']))
		$pid=intval($_POST['pid']);
	if (isset($_POST['quantity']))
		$new_quantity=intval($_POST['quantity']);
	if (isset($_POST['my_action']))
		$myaction=$_POST['my_action'];

	$currency=null; // hhee, trick to save last config, for currency format to cart total
	$cart_count=0;
	$cart_total=0;
	$cart_total_saving=0;
	$bk_price_total=0;

	$backup_carts=array();

	foreach ($carts as $v)
	{
		if (($myaction == "remove") && ($v->id == $pid))
			continue;
		// update cart
		if ($v->id == $pid)
			$v->quantity = $new_quantity;

		$backup_carts[]=clone $v;

		$cart_count+=$v->quantity;
		// get config
		$config=$db->selectObject("productsmodule_config", "location_data = '{$v->location_data}'");
		$currency=productsmodule::_GetCurrencyDefault($config->currency_id);
		// calculate total of this cart
		$temp=$v->quantity;
		if ($v->on_sale)
			$temp*=$v->price_sale_bk;
		else
			$temp*=$v->price_bk;
		$cart_total_saving+=$v->price_save_bk * $v->quantity;
		$cart_total+=$temp;
		$v->price_total_value=$temp;
		$temp=productsmodule::_GetCurrencyFormat($currency, $temp);
		$v->price_total=$temp;
		if ($v->id == $pid)
			$bk_price_total=$v->price_total;
	}
	$cart_tax=0.1*$cart_total;
	$cart_tax=productsmodule::_GetCurrencyFormat($currency, $cart_tax);
	$cart_total2 = $cart_tax + $cart_total;
	$cart_total = productsmodule::_GetCurrencyFormat($currency, $cart_total);
	// total included tax
	$cart_total2 = productsmodule::_GetCurrencyFormat($currency, $cart_total2);
	$cart_total_saving = productsmodule::_GetCurrencyFormat($currency, $cart_total_saving);
	$cart_shipping = productsmodule::_GetCurrencyFormat($currency, 0);

	// update the cart into session
	exponent_sessions_set(ABProductsModule_Carts, $backup_carts);

	// return json
	$obj=null;
	$obj->action=$myaction;
	$obj->pid=$pid;
	$obj->cart_count = $cart_count;
	$obj->cart_total = $cart_total;
	$obj->cart_total2 = $cart_total2;
	$obj->cart_total_saving= $cart_total_saving;
	$obj->cart_tax= $cart_tax;
	$obj->product_price_total= $bk_price_total;
	echo json_encode($obj);
	// force ajax action 
	exponent_theme_setFlagAjaxAction(true);
?>
